package com.easyban.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easyban.common.BaseContext;
import com.easyban.common.R;
import com.easyban.entity.Guestbook;
import com.easyban.entity.News;
import com.easyban.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/news")
@Slf4j
public class NewsController {
    @Autowired
    private NewsService newsService;

    @PostMapping
    public R<String> addNews(@RequestBody News news) {
        if (!news.getUserId().equals(BaseContext.getCurrentId())){
            return R.error("用户id不一致");
        }
        newsService.save(news);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page<News>> getNews(int page, int pageSize, String name) {
        log.info("执行分页查询....");
        //构造分页构造器
        Page<News> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(StringUtils.isNoneEmpty(name), News::getTitle, name);

        queryWrapper.orderByDesc(News::getCreateTime);

        newsService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    @DeleteMapping("/{id}")
    public R<String> deleteNews(@PathVariable Long id) {
        newsService.removeById(id);
        return R.success("删除成功");
    }

    @GetMapping("/{id}")
    public R<News> getNews(@PathVariable Long id) {
        return R.success(newsService.getById(id));
    }

    @PutMapping()
    public R<String> updateNews(@RequestBody News news) {
        newsService.updateById(news);
        return R.success("修改成功");
    }
}
